package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pet-sys/cache"
	"pet-sys/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	sx := c.PostForm("sx")
	img := c.PostForm("img")
	name := c.PostForm("name")
	if sx == "" || img == "" || name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	data := models.Pet{
		Sx:   sx,
		Img:  img,
		Name: name,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "1"))
	offset := (page - 1) * size
	var pet []models.Pet

	redis_key := "list_pet"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&pet)
		jsonData, _ := json.Marshal(pet)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &pet)
	}

	var count int64
	models.DB.Model(&models.Pet{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表查询成功",
		"data":  pet,
		"count": count,
	})
	return
}
